package es.ats.codington.festival.daos;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.imageio.ImageIO;

import es.ats.codington.festival.domain.Image;
import es.ats.codington.festival.exceptions.DAOException;
import es.ats.codington.festival.interfaces.daos.IImageDAO;
import es.ats.codington.festival.utils.FERSDataConnection;
import es.ats.codington.festival.utils.FERSDbQuery;

public class ImageDAOImp implements IImageDAO{
	private FERSDataConnection con;
	private FERSDbQuery query;
	
	public ImageDAOImp() {
		con = new FERSDataConnection();
		query = new FERSDbQuery();
    }
    	
    public FERSDataConnection getCon() {
		return con;
	}

	public void setCon(FERSDataConnection con) {
		this.con = con;
	}

	public FERSDbQuery getQuery() {
		return query;
	}

	public void setQuery(FERSDbQuery query) {
		this.query = query;
	}
	
	@Override
	public Image getPhotoById(int photoId) throws DAOException{
		try{
	    	PreparedStatement pStmt = con.prepareStatement(query.checkPhotoById());
	    	pStmt.setInt(1,photoId);
	    	ResultSet rs = pStmt.executeQuery();
	    	Image i=new Image();
			if (rs.next()) {
				Blob b=rs.getBlob("photo");
				InputStream stream = b.getBinaryStream();
				BufferedImage img = ImageIO.read(stream);
				i.setPhoto(img);
				i.setImageId(photoId);
				String type=rs.getString("type");
				i.setType(type);
				return i;
			}
			else{
				throw new DAOException("DB getPhotoById failure: empty resulset");
			}
		} catch (Exception ex) {
			throw new DAOException("DB getPhotoById failure:"+ex.getMessage(), ex);
		}
	}

	@Override
	public int insertImage(Image img) throws DAOException {
		try{
			BufferedImage image = img.getPhoto();
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			ImageIO.write(image, img.getType(), os);
			InputStream is = new ByteArrayInputStream(os.toByteArray());
	    	PreparedStatement pStmt = con.prepareStatement(query.insertPhoto());
	    	pStmt.setBinaryStream(1, is, os.size());
	    	pStmt.setString(2,img.getType());
	    	pStmt.executeUpdate();
			ResultSet resultSet = pStmt.getGeneratedKeys();
			if (resultSet.next()){
				return resultSet.getInt(1);
			}
			else{
				return 0;
			}
		} catch (Exception ex) {
			throw new DAOException("DB inserImage failure:"+ex.getMessage(), ex);
		}
	}

}
